<script lang="ts" setup>
import type { SmsTemplateVO } from '#/api/config/template/sms/model';

import { computed, onMounted, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VbenIcon } from '@vben/icons';

import { Button, Select, Spin } from 'ant-design-vue';

import { smsTemplateList } from '#/api/config/template/sms';
import smsPreviewModal from '#/views/config/template/sms/components/sms-preview-modal.vue';

interface Props {
  multiple?: boolean;
  all?: boolean;
  allowClear?: boolean;
  options?: SmsTemplateVO[];
}

const props = withDefaults(defineProps<Props>(), {
  multiple: false,
  all: true,
  allowClear: false,
  options: () => [],
});

const emit = defineEmits(['blur', 'change', 'select']);
const loading = ref(false);
const list = ref<SmsTemplateVO[]>([]);
const modelValue = defineModel<any>('value', {
  default: () => undefined,
});

const mode = computed(() => {
  return props.multiple ? 'multiple' : undefined;
});

watch(
  () => props.all,
  async (val) => {
    if (val) {
      // 切换为查询全部模板
      await getList();
    }
  },
);

async function getList() {
  loading.value = true;
  const results = await smsTemplateList({ status: '0' });
  list.value = results || [];
  loading.value = false;
}

onMounted(async () => {
  if (props.all) {
    await getList();
  } else {
    list.value = [...props.options];
  }
});

function handleChange(val: any) {
  console.log(val);
  emit('change', modelValue.value);
}

// 预览邮件模板
const [SmsPreviewModal, smsPreviewModalApi] = useVbenModal({
  connectedComponent: smsPreviewModal,
});

async function handlePreview(id: number | string) {
  smsPreviewModalApi.setData({ id });
  smsPreviewModalApi.open();
}
</script>
<template>
  <div class="flex w-full items-center gap-1">
    <Select
      v-model:value="modelValue"
      class="flex-1"
      placeholder="请选择"
      :mode="mode"
      show-search
      :options="list"
      option-filter-prop="smsName"
      :field-names="{ label: 'smsName', value: 'id' }"
      @blur="emit('blur')"
      @change="handleChange"
    >
      <template v-if="loading" #notFoundContent>
        <Spin size="small" />
      </template>
    </Select>
    <Button v-if="modelValue && !multiple" @click="handlePreview(modelValue)">
      <VbenIcon icon="icon-park-outline:preview-open" />
      <!--预览-->
    </Button>
    <SmsPreviewModal />
  </div>
</template>
